/**
 * 发送消息
 */
export function sendMessage(message, request) {
    // 初始化
    sendMessageInit(message, request);

    // 传递上下文
    uni.$u.http.api.context({
        id: request.chat.id,
        context: request.requestContext
    }).then(data => {
        if (data) {
            sseChatStart(data, request); // 开始sse请求
        } else {
            sseChatClose(request);
        }
    }).catch(err => {
        sseChatClose(request);
    })
}

/**
 * sse 初始化
 */
function sendMessageInit(message, request) {
    // 添加新的消息到消息列表中
    const chatMessages = request.chat.messages;
    chatMessages.push(uni.$u.chat.newUseMessage(message));

    request.streamMsg = "";
    request.lastRenderTimes = uni.$u.chat.curTime(); // 最后一次渲染时间
    request.requestContext = []; // 本次请求得上下文

    // 添加聊天设置的上下文
    for (let context of request.chat.context) {
        request.requestContext.push({
            "role": context.role,
            "content": context.content
        });
    }

    // 获取历史消息的数量
    const historyMessageCount = request.chat.config.historyMessageCount
        ? request.chat.config.historyMessageCount : 1;
    let i = Math.max(chatMessages.length - historyMessageCount, 0);
    // 添加历史消息
    for (i; i < chatMessages.length; i++) {
        let requestMessage = {
            "role": chatMessages[i].role,
            "content": chatMessages[i].content
        };
        request.requestContext.push(requestMessage);
    }

    request.renderTimeInterval = uni.$u.chat.getRenderTimeInterval(chatMessages.length); // 渲染时间间隔
    request.newMessage = uni.$u.chat.newMessage(); // 新消息
    chatMessages.push(request.newMessage);
    request.updateVuexChatList(request); // 更新缓存
    request.delayedScrollToBottom(); // 滚动消息到底部
}

/**
 * sse 开始
 */
function sseChatStart(id, request) {
    // 获取 sse 请求的 get参数
    const param = uni.$u.chat.jsonToGetParam(request.chat.config);
    // 创建 sse 链接
    request.eventSource = new EventSource(uni.$u.http.api.sseUrl + '?id=' + id + "&" + param);
    // 监听 sse 消息
    request.eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data).data;
        if (data === "[DONE]") {
            sseChatClose(request); // 关闭 sse 链接
        } else {
            request.streamMsg += data;
            if (request.lastRenderTimes < uni.$u.chat.curTime() - request.renderTimeInterval) {
                sseChatRenderText(request);
                request.lastRenderTimes = uni.$u.chat.curTime();
            }
        }
    };
    // 监听 sse 消息异常
    request.eventSource.onerror = (event) => {
        console.log('SSE connection closed, event: ', JSON.stringify(event));
        sseChatClose(request);
    };
}

/**
 * 关闭sse链接
 */
function sseChatClose(request) {
    request.streamMsg = uni.$u.chat.streamCloseMsg(request.streamMsg);
    sseChatRenderText(request, true);
    request.newMessage.streaming = false;
    if (request.eventSource) {
        request.eventSource.close();
        summaryTopic(request);
        request.updateVuexChatList(request);
    }
}

/**
 * 总结主题
 */
function summaryTopic(request) {
    if (!request.chat.topic || request.chat.topic === uni.$u.chat.defaultTopic) {
        const messages = request.chat.messages;
        if (messages && messages[messages.length - 1].content === uni.$u.chat.streamErrorMsg) {
            return;
        }
        uni.$u.http.api.summaryTopic({context: messages}).then(data => {
            if (data) {
                request.chat.topic = data.length > 20 ? data.substring(0, 20) : data;
                request.updateVuexChatList(request);
            }
        });
    }
}

/**
 * 渲染sse接收到的消息
 * @param flag 防止递归调用。
 */
function sseChatRenderText(request, flag) {
    if (request.newMessage.streaming || flag) {
        request.newMessage.content = request.streamMsg;
        request.scrollToBottom(2);
    } else {
        sseChatClose(request);
    }
}